<template>
  <div class="common-map">
    <div id="map-container"
      class="map-container"></div>

    <div class="clip-btn-groups"
      v-if="!clipLineShow && !clipPolygonShow"
      @mouseleave="isClipState = false"
      @mouseover="isClipState = true">
      <div v-show="isClipState"
        class="map-btns">
        <div class="map-btn">
          <div class="map-operation-btn clip-line-btn "
            @click="mapBtnShowClick('clipLine')"><i />线分割</div>
        </div>
        <div class="map-btn">
          <div class="map-operation-btn clip-polygon-btn"
            @click="mapBtnShowClick('clipPolygon')"><i />面分割</div>
        </div>
      </div>

      <div class="map-btn clip-spot-btn">
        <div><i />分割</div>
      </div>
    </div>

    <div class="clip-btn-groups"
      v-if="clipLineShow"
      @mouseleave="isClipState = false"
      @mouseover="isClipState = true">
      <div v-show="isClipState"
        class="map-btns">
        <div class="map-btn">
          <div class="map-operation-btn cancal"
            @click="mapOperationClear('clipLine')"><i />清除</div>
        </div>
        <div class="map-btn">
          <div class="map-operation-btn complete"
            @click="mapOperationComplete('clipLine')"><i />完成</div>
        </div>
      </div>
      <div class="map-btn clip-line-btn-active">
        <div><i />线分割</div>
      </div>
      <MapFeatureSplitAdsorbPlugin :map="map"
        :feature="feature"
        :state="isClipLineState" />
    </div>

    <div class="clip-btn-groups"
      v-if="clipPolygonShow"
      @mouseleave="isClipState = false"
      @mouseover="isClipState = true">
      <div v-show="isClipState"
        class="map-btns">
        <div class="map-btn">
          <div class="map-operation-btn cancal"
            @click="mapOperationClear('clipPolygon')"><i />清除</div>
        </div>
        <div class="map-btn">
          <div class="map-operation-btn complete"
            @click="mapOperationComplete('clipPolygon')"><i />完成</div>
        </div>
      </div>

      <div class="map-btn clip-line-btn-active">
        <div><i />面分割</div>
      </div>
    </div>

  </div>
</template>

<script>
  import './Leaflet.Editable.js';
  import polygonClipUtil from './PolygonClipUtil.js';
  import MapFeatureSplitAdsorbPlugin from './MapFeatureSplitAdsorbPlugin.vue';
  import { splitGeometry } from '@/api/module/systemApi.js';

  const wellknown = require('wellknown');

  const mapConfig = {
    // 基础底图
    baseLayerUrl: 'http://t{s}.tianditu.gov.cn/DataServer?T=img_c&X={x}&Y={y}&L={z}&tk=ffa5ef8e4ea43caf693fa0097f8258a6',
    // 基础底图注记
    baseLabelLayer: 'http://t{s}.tianditu.gov.cn/DataServer?T=cia_c&X={x}&Y={y}&L={z}&tk=ffa5ef8e4ea43caf693fa0097f8258a6'
  };
  const f_shape =
    'MULTIPOLYGON(((103.24666097058889 25.664670243522767,103.24667920851691 25.66464028612689,103.24670783822187 25.664596103150025,103.24673303461542 25.664554165663738,103.24675294454559 25.664522818066345,103.2467738677689 25.664491615240795,103.24678333276901 25.664477474289118,103.24679298888384 25.66446456952704,103.246803114012 25.66445103891308,103.24681162610396 25.664442560463733,103.24682713908767 25.664426228390393,103.2468498471601 25.664404485088845,103.24686521360121 25.66439029371593,103.24690311168284 25.66436061644053,103.24691689295484 25.664349178241274,103.2469278558659 25.66434007911439,103.24694710986327 25.664326771041026,103.24697162670925 25.66431003756649,103.24698404804039 25.664301559552577,103.24699997763163 25.66429282683254,103.24702934827631 25.664279394405153,103.24706338653546 25.664268787629208,103.24709680787375 25.66425971455491,103.24718544842241 25.664237210613297,103.24720753475978 25.6642327235688,103.24725068619684 25.664226862456083,103.24727752980353 25.664223767516308,103.24728776815105 25.664221795533095,103.24733422409702 25.66421284792583,103.24735947969278 25.664206632500303,103.24737443508448 25.664202952317787,103.24741807599672 25.66419350527447,103.24745674544039 25.664187443688657,103.24748672134221 25.664184045312563,103.24749517320258 25.664183087236307,103.24751096319821 25.66418123294875,103.24753783362264 25.664180716717453,103.24755567385105 25.6641808485213,103.24764566179284 25.664181514319957,103.24768490709936 25.66418519058374,103.24772817407349 25.66418474127848,103.24775581326678 25.66418211688921,103.24778895763384 25.664176819061016,103.24783443769422 25.664166878280025,103.24789401292394 25.664146152653387,103.24791099296812 25.664137124300808,103.2479379561802 25.664120841775564,103.24795623926258 25.664109800911884,103.24798729723568 25.664086324482422,103.24801100058312 25.66406842585658,103.24803135939995 25.664049864486856,103.24805039832033 25.66403107568139,103.24807701066091 25.66400577442312,103.2481158426507 25.663961436252023,103.24813318186696 25.663942337059996,103.24815416826809 25.663917246355414,103.24817196350364 25.66389340586942,103.2481769797465 25.663886625118902,103.24818493424083 25.663875872468317,103.24821813521007 25.66382643077623,103.24822964504928 25.663808279446854,103.24824519331679 25.663783216285427,103.2482660706365 25.663739860156035,103.24824889023087 25.663762442680262,103.24812746897152 25.66392204510266,103.24798842860343 25.663893674788806,103.24795815338679 25.663727689985947,103.24792784550714 25.66356171537795,103.24798339638754 25.663420908408373,103.24773783548805 25.66337286726597,103.24773032440697 25.663371398526323,103.24767681913154 25.66342081738359,103.24765017867973 25.663445423408852,103.24759310906826 25.66349813355406,103.24703139993093 25.663547202657757,103.24709755745248 25.663642580165693,103.24702498535588 25.663724523804323,103.24697005078396 25.663909814141842,103.2468201699937 25.66391411763694,103.2467127274947 25.663917202877574,103.24669091988666 25.663917845385804,103.24669480985806 25.663929015290414,103.24670795900975 25.663966775027333,103.24674285945532 25.66399857094957,103.2467666405334 25.66401517927175,103.24679277522459 25.664019904150084,103.24680296509952 25.664021746264808,103.24682501216431 25.664033784075468,103.24684363192253 25.664040502305053,103.24685633385376 25.664045743101283,103.24686076353112 25.664066337143275,103.24685169653472 25.66408628204243,103.24683240073749 25.664095616610904,103.2468173523292 25.66410797176902,103.24679454924483 25.664104345697947,103.24678942714682 25.664098276152213,103.24675159948953 25.664109297456285,103.2467012362703 25.66413112399424,103.24670225450652 25.664147926311863,103.24670255212904 25.664171469028595,103.246630282292 25.66421506943119,103.24659597173141 25.664260256245242,103.24655963304316 25.66431310166262,103.2465315363441 25.664347728110076,103.24649844196247 25.664381691004326,103.24649399410195 25.66438625564184,103.24646574840497 25.66440655610272,103.24644271274829 25.66442108053284,103.24642186359024 25.664443227575347,103.24641183127244 25.664492027426768,103.24644805999705 25.66452992537334,103.24647716816597 25.664549324903252,103.24647777687154 25.664549730356725,103.24648328437104 25.66457260763669,103.24647724920385 25.66460035969723,103.24648043065449 25.664602242735292,103.24646155049746 25.664611000599546,103.24644503044561 25.664624155297858,103.24643123690313 25.664635139134173,103.24640189737947 25.664651627604325,103.24636393842813 25.664650041559856,103.24633289846993 25.664705707214036,103.24630083181535 25.664763822076363,103.24634318578238 25.664764423848233,103.24634325648259 25.664764423244478,103.24630644564195 25.665134089398094,103.24635744949425 25.665135853314105,103.24636536053588 25.665136126912152,103.24637672832046 25.665120413319038,103.24639021802327 25.665104098568097,103.24641576818483 25.66507044786946,103.24642129810985 25.665060618097066,103.24642508217518 25.665053891248228,103.2464432918324 25.665028099758405,103.24644611487126 25.665024101348383,103.24646729722139 25.664983324997948,103.2464870464689 25.664944939507663,103.2465000391523 25.66491731936212,103.24651572602724 25.664885282227257,103.246532673563 25.66485285255247,103.24656913175045 25.664797261519688,103.24659593319882 25.66476371562808,103.24661439556569 25.664739105630616,103.24662784863966 25.664719275809333,103.24665353540169 25.66468125023423,103.24666097058889 25.664670243522767)))';

  export default {
    name: 'theMap',
    components: { MapFeatureSplitAdsorbPlugin },
    data() {
      return {
        map: null,
        spotGroup: null,
        feature: null,
        // 按钮显隐状态，可公用
        isClipState: false,
        // 显隐线操作
        clipLineShow: false,
        // 显隐面操作
        clipPolygonShow: false,
        // 开启线操作
        isClipLineState: false,
        isClipProjectShape: false
        // 图斑分组
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        //初始化
        this.map = L.map('map-container', {
          crs: L.CRS.EPSG4326, //坐标系
          center: [35.639, 105.55],
          zoom: 4,
          // 隐藏右下角官方图标
          attributionControl: false,
          // 隐藏左上角zoom控制图标(+ - 按钮)
          zoomControl: false,
          // doubleClickZoom: false
          // 引入Leaflet.Editable插件
          editable: true
        });

        //引入图层
        L.tileLayer(mapConfig.baseLayerUrl, {
          subdomains: ['0', '1', '2', '3', '4'],
          zoomOffset: 1,
          // 超过17级进行放大，保证不会出现未找到服务的提示
          maxNativeZoom: 17,
          maxZoom: 20
        }).addTo(this.map);

        //引入注记
        L.tileLayer(mapConfig.baseLabelLayer, {
          subdomains: ['0', '1', '2', '3', '4'],
          zoomOffset: 1
        }).addTo(this.map);

        // 图斑形状
        this.spotGroup = new L.FeatureGroup();
        this.spotGroup.addTo(this.map);

        // 绘制形状的集合
        this.drawGroup = new L.FeatureGroup();
        this.drawGroup.addTo(this.map);
      },
      polylineDraw() {
        this.map.editTools.startPolyline();
      },
      polygonDraw() {
        this.map.editTools.startPolygon();
      },
      toBounds(bounds) {
        if (bounds) {
          this.map.fitBounds(bounds);
        } else {
          this.map.flyTo([35.639, 105.55], 4);
        }
      },
      addSpot() {
        let wkt = f_shape.split(';').pop();
        let geojson = wellknown.parse(wkt);
        this.feature = L.geoJSON(geojson, {
          style: { color: '#f00', weight: 1 }
        });
        this.spotGroup.addLayer(this.feature);
        this.map.fitBounds(this.feature.getBounds());
      },
      // 清除所有
      clearAll() {
        this.spotGroup.clearLayers();
        this.map.editTools.featuresLayer.clearLayers();
        this.map.editTools.stopDrawing();
        this.resetBtnStatus();
      },
      // 切割图斑部分
      mapBtnShowClick(type) {
        if (!this.feature) {
          this.$message.warning('没有可分割的图斑！');
          return;
        }
        if ('clipLine' === type) {
          this.isClipLineState = true;
          this.clipLineShow = true;
          // 开启Leaflet.Editable的画线方法
          this.map.editTools.startPolyline();
        } else if ('clipPolygon' === type) {
          this.clipPolygonShow = true;
          // 开启Leaflet.Editable的画面方法
          this.map.editTools.startPolygon();
        }
      },
      mapOperationComplete(type) {
        this.doClipProjectShape();
        // this.mapBtnClick(type);
      },
      mapOperationClear(type) {
        this.map.editTools.featuresLayer.clearLayers();
        this.map.editTools.stopDrawing();
      },
      resetBtnStatus() {
        this.isClipState = false;
        this.clipLineShow = false;
        this.clipPolygonShow = false;
        this.isClipLineState = false;
      },
      doClipProjectShape() {
        let clipFeatures = this.map.editTools.featuresLayer.toGeoJSON(12);
        if (clipFeatures && clipFeatures.features && clipFeatures.features.length < 1) {
          this.$message.warning('分割不合理，请重试!');
          return;
        }
        if (
          clipFeatures &&
          clipFeatures.features &&
          clipFeatures.features.length > 1 &&
          clipFeatures.features[0].geometry &&
          clipFeatures.features[0].geometry.type == 'Polygon'
        ) {
          clipFeatures = polygonClipUtil.polygons2MultiPolygon(clipFeatures);
        }

        // 获取图斑的GeoJson
        let poly = this.feature.toGeoJSON(12).features[0];
        // 避免丢失精度，获取内置WKT进行转换
        let polyShape = this.feature.f_shape;
        if (polyShape && polyShape.toLocaleLowerCase().indexOf('multipolygon') > -1) {
          try {
            let _poly = Terraformer.WKT.parse(polyShape);
            poly.geometry = _poly;
          } catch (e) {
            console.log(e);
          }
        }
        if (poly && poly.geometry && poly.geometry.type == 'MultiPolygon') {
          poly = polygonClipUtil.multiPolygon2polygons(poly);
        }
        poly = poly.length > 0 ? poly[0] : poly;
        let isSplit = true;
        if (clipFeatures.features[0].geometry.type == 'LineString') {
          isSplit = clipFeatures.features[0].geometry.coordinates.length > 1;
        } else if (clipFeatures.features[0].geometry.type == 'Polygon') {
          isSplit = clipFeatures.features[0].geometry.coordinates[0].length > 2;
        }

        if (isSplit) {
          splitGeometry(poly, clipFeatures)
            .then((response) => {
              console.log(222, response);
              let status = response.status;
              if (!status === 'OK') {
                this.$message.error('切割失败：' + response.message);
                return;
              }
              let data = response.data;
              this.$emit('saveClipTBGemotrys', data);
            })
            .catch((e) => {
              this.$message.warning('分割不合理，请重试!');
              //this.$message.warning('切割失败2：' + e.message);
            });
        } else {
          this.$message({
            type: 'warning',
            message: '绘制图形不合理，请重新绘制'
          });
        }
        this.map.editTools.featuresLayer.clearLayers();
        console.log('结束编辑');
        this.isClipProjectShape = false;
      }
      // 图斑分组
    }
  };
</script>

<style lang="scss" scoped>
  .common-map {
    width: 100%;
    height: 100%;
    .map-container {
      width: 100%;
      height: 100%;
    }
    // 按钮
    .clip-btn-groups {
      position: absolute;
      top: 100px;
      right: 20px;
      z-index: $--zindex-map-float-box;
    }
    .map-btn {
      display: inline-block;
      width: 60px;
      height: 60px;
      position: relative;
      color: #0072c5;
      background-color: rgba(255, 255, 255, 0.8);
      border-radius: 4px;
      padding: 4px;
      box-sizing: border-box;
      cursor: pointer;
      text-align: center;
      margin-left: 6px;
      font-size: 14px;
    }
    .map-btn i {
      display: block;
      width: 32px;
      height: 32px;
      margin: 0 auto 4px auto;
    }
    .map-btns {
      display: inline-block;
    }
    .map-operation-btn:hover {
      background-color: rgba(0, 114, 197, 0.2);
    }

    .clip-spot-btn i {
      background: url('../images/split.png') no-repeat center;
    }
    .clip-line-btn i {
      background: url('../images/splitline.png') no-repeat center;
    }
    .clip-polygon-btn i {
      background: url('../images/splitpolygon.png') no-repeat center;
    }
    .clip-line-btn-active {
      color: #fff;
      background-color: #0072c5;
      i {
        background: url('../images/splitline_active.png') no-repeat center;
      }
    }
    .clip-polygon-btn-active {
      color: #fff;
      background-color: #0072c5;
      i {
        background: url('../images/splitpolygon_active.png') no-repeat center;
      }
    }
    .map-operation-btn.complete i {
      background: url('../images/complete.png') no-repeat center;
    }
    .map-operation-btn.cancal i {
      background: url('../images/clear.png') no-repeat center;
    }
  }
</style>
